//
//  DCHttpClient.m
//  DCProject
//
//  Created by bigbing on 2019/4/22.
//  Copyright © 2019 bigbing. All rights reserved.
//

#import "DCHttpClient.h"
#import "DCNavigationController.h"
#import "MXLoginController.h"

#if __has_include(<AFNetworking/AFNetworking.h>)
    #import <AFNetworking/AFNetworking.h>


static NSString * BASIC_URL;

@interface DCHttpClient ()
{
    AFHTTPSessionManager *_manager;
    AFHTTPSessionManager *_manager2;
}
@end

@implementation DCHttpClient


#pragma mark - 单列
+ (DCHttpClient *) shareClient {
    static DCHttpClient * _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[[self class] alloc] init];
    });
    return _instance;
}


#pragma mark - 设置基础的请求地址
+ (void)setBaseUrl:(NSString *)baseUrl{
    BASIC_URL = baseUrl;
}


#pragma mark - 初始化
- (instancetype)init{
    self = [super init];
    if (self) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",nil];
        _manager.requestSerializer.timeoutInterval = 30.0f;
//        _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        _manager.requestSerializer.timeoutInterval = 30;
//        _manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//        [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//        [_manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//        [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Disposition"];
//       [_manager.requestSerializer setValue:APP_VERSION forHTTPHeaderField:@"version"];
//        
//        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
        
        _manager.securityPolicy.allowInvalidCertificates = YES;
        
        
        
        
        _manager2 = [AFHTTPSessionManager manager];
        _manager2.requestSerializer = [AFJSONRequestSerializer serializer];
        _manager2.responseSerializer = [AFHTTPResponseSerializer serializer];
        _manager2.requestSerializer.timeoutInterval = 30.0f;
        
        if (!BASIC_URL) {
            BASIC_URL = DC_RequestUrl;
        }
    }
    return self;
}



#pragma mark - 发送请求
- (void)requestWithPath:(NSString *)path
                 params:(NSDictionary *)params
             httpMethod:(DCHttpRequestType)method
                 sucess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
               failture:(void (^)(NSURLSessionDataTask *task, NSError *error))failture{
    
    NSString * url = BASIC_URL;
    
    if (path && ([path containsString:@"https"] || [path containsString:@"http"])) {
        url = path;
    } else if (path && [path length] > 0){
        url = [url stringByAppendingString:path];
    }
    
    NSMutableDictionary * paramsNow = [[NSMutableDictionary alloc] initWithDictionary:params];
    [paramsNow setObject:@"app" forKey:@"client"];
    [paramsNow setObject:@"ios" forKey:@"client_type"];
    [paramsNow setObject:@"app" forKey:@"clienform"];//商品详情相关
    
    // 本地token是否存在
    NSString * token = [DCObjectManager dc_readUserDataForKey:DC_Token_Key];
    if (token) {
        [_manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
        
    } else {
        [_manager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
    }
    MJWeakSelf
    [self requestWithURLString:url params:paramsNow httpMethod:method sucess:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary * dict = [responseObject mj_JSONObject];
        
        NSLog(@"url - %@,\n params - %@, \n response success - %@",url,paramsNow,dict);
        
        if (dict && dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_TokenOut) {
            // 需要登陆
            MXUserInfoModel *model = [[MXUserInfoModel alloc] init];
            [DCCacheTool saveUserInfo:model];
            
            UIWindow *window = [weakSelf getKeyWindow];
            window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[MXLoginController alloc] init]];
            [window makeKeyAndVisible];
        } else {
            if (success) {
                success(task,responseObject);
            }
        }
        
    } failture:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@" url - %@,\n params - %@, \n response error - %@",url,paramsNow,error);
        
        [SVProgressHUD dismiss];
        [DC_KeyWindow dc_enable];
        if (failture) {
            failture(task,error);
        }
    }];
}

- (UIWindow *)getKeyWindow {
    
    UIWindow *keyWindow;
    if (@available(iOS 13.0, *)) {
        
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                
                keyWindow = windowScene.windows.firstObject;
                break;
            }
        }
    }
    return keyWindow;
}

#pragma mark -  发送请求 带根地址
- (void)requestWithBaseUrl:(NSString *)baseUrl
                      path:(NSString *)path
                    params:(NSDictionary *)params
                httpMethod:(DCHttpRequestType)method
                    sucess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                  failture:(void (^)(NSURLSessionDataTask *task, NSError *error))failture
{
    NSString * url = baseUrl;
    
    if (path && [path length] > 0){
        url = [url stringByAppendingString:path];
    }
    
//    // 本地token是否存在
//    NSString * token = [DCObjectManager dc_readUserDataForKey:DC_Token_Key];
//    if (token) {
//        [_manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//        
//    } else {
//        [_manager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
//    }
//    
    
    [_manager2 GET:url parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url - %@,\n params-----%@,\n response success - %@",url,params,responseObject);
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"url - %@,\n params-----%@,\n response error - %@",url,params,error);
        
        [SVProgressHUD dismiss];
        [DC_KeyWindow dc_enable];
        if (failture) {
            failture(task,error);
        }
    }];
    
    
//    [self requestWithURLString:url params:params httpMethod:method sucess:^(NSURLSessionDataTask *task, id responseObject) {
//        NSLog(@"url - %@,\n params-----%@,\n response success - %@",url,params,responseObject);
//        NSDictionary * dict = [responseObject mj_JSONObject];
//        
//        NSLog(@"url - %@,\n params-----%@,\n response success - %@",url,params,dict);
//        
//        if (success) {
//            success(task,responseObject);
//        }
//        
//    } failture:^(NSURLSessionDataTask *task, NSError *error) {
//        
//        NSLog(@"url - %@,\n params-----%@,\n response error - %@",url,params,error);
//        
//        [SVProgressHUD dismiss];
//        [DC_KeyWindow dc_enable];
//        if (failture) {
//            failture(task,error);
//        }
//    }];
}



#pragma mark - 具体请求
- (void)requestWithURLString:(NSString*)URLString
                      params:(NSDictionary*)params
                  httpMethod:(DCHttpRequestType)method
                      sucess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                    failture:(void (^)(NSURLSessionDataTask *task, NSError *error))failture{
    
    switch (method) {
        case DCHttpRequestGet:
        {
            [_manager GET:URLString parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                success(task,responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failture(task,error);
            }];
            
        }
            break;
        case DCHttpRequestPost:
        {
            [_manager POST:URLString parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                success(task,responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failture(task,error);
            }];
            
            
        }
            break;
        case DCHttpRequestJsonPost:
        {
            
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            //设置 AFHTTPResponseSerializer
            AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
            responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"text/json",
                                                         @"text/javascript",
                                                         @"text/plain",
                                                         nil];
            manager.responseSerializer = responseSerializer;
            
            NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:params error:nil];
            request.timeoutInterval = 10.f;
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            
            NSString * app_verson = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
            
            [request setValue:app_verson forHTTPHeaderField:@"version"];
            
            // 本地token是否存在
            NSString * token = [DCObjectManager dc_readUserDataForKey:DC_Token_Key];
            if (token) {
                [request setValue:token forHTTPHeaderField:@"token"];
                
            } else {
                [request setValue:@"" forHTTPHeaderField:@"token"];
            }
            
            NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
                
            } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
                
            } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                
                if (!error) {
                    
                    if (success) {
                        success(task,responseObject);
                    }
                    
                } else {
                    
                    if (failture) {
                        failture(task,error);
                    }
                }
                
            }];
            [task resume];
            
        }
            break;
        default:
            break;
    }
    
}


#pragma mark - 上传图片
- (void)requestUploadWithPath:(NSString *)path
                       images:(NSArray *)images
                     fileName:(NSString *)fileName
                     progress:(void(^)(NSProgress * uploadProgress))progress
                       sucess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                     failture:(void (^)(NSURLSessionDataTask *task, NSError *error))failture{
    
    NSString * url = BASIC_URL;
    
    NSString * URLString = [NSString stringWithFormat:@"%@",url];
    if (path && [path length]>0) {
        URLString = [URLString stringByAppendingString:path];
    }
    
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params setObject:@"app" forKey:@"client"];
    [params setObject:@"ios" forKey:@"client_type"];
    [params setObject:@"app" forKey:@"clienform"];//商品详情相关

    
    [_manager POST:URLString parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 利用时间戳当做图片名字
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        
        for (int i = 0; i < [images count]; i++) {
            NSString * imageName = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:[NSDate date]]];
            
            UIImage * image = images[i];
            NSData * data = UIImageJPEGRepresentation(image, 1);
            
            // 如果图片大于1M  将图片压缩到200kb左右
            if ([data length] > 1024000) {
                CGFloat compress = 200 / [data length];
                data = UIImageJPEGRepresentation(image, compress);
            }
            
            [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"%@[%d]",fileName,i] fileName:imageName mimeType:@"image/jpg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url - %@,\n params-----%@,\n response success - %@",url,params,[responseObject mj_JSONObject]);
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"url - %@,\n params-----%@,\n response error - %@",url,params,[error mj_JSONObject]);
        if (failture) {
            failture(task,error);
        }
    }];
    //    [_manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //        // 利用时间戳当做图片名字
    //        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    //        formatter.dateFormat = @"yyyyMMddHHmmss";
    //
    //        for (int i = 0; i < [images count]; i++) {
    //
    //            NSString * imageName = [formatter stringFromDate:[NSDate date]];
    //            NSString * fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
    //
    //            UIImage * image = images[i];
    //            NSData * data = UIImageJPEGRepresentation(image, 1);
    //
    //            // 如果图片大于1M  将图片压缩到200kb左右
    //            if ([data length] > 1024000) {
    //                CGFloat compress = 200 / [data length];
    //                data = UIImageJPEGRepresentation(image, compress);
    //            }
    //
    //            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
    //        }
    //
    //    } progress:progress success:success failure:failture];
}


#pragma mark - 上传图片(单图)
- (void)requestUploadWithPath:(NSString *)path
                       image:(UIImage *)image
                     fileName:(NSString *)fileName
                     progress:(void(^)(NSProgress * uploadProgress))progress
                       sucess:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                     failture:(void (^)(NSURLSessionDataTask *task, NSError *error))failture{
    
    NSString * url = BASIC_URL;
    
    NSString * URLString = [NSString stringWithFormat:@"%@",url];
    if (path && [path length]>0) {
        URLString = [URLString stringByAppendingString:path];
    }
    
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params setObject:@"app" forKey:@"client"];
    [params setObject:@"ios" forKey:@"client_type"];
    [params setObject:@"app" forKey:@"clienform"];//商品详情相关
    
    [_manager POST:URLString parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 利用时间戳当做图片名字
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString * imageName = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:[NSDate date]]];
        
        NSData * data = UIImageJPEGRepresentation(image, 1);
        
        // 如果图片大于1M  将图片压缩到200kb左右
        if ([data length] > 1024000) {
            CGFloat compress = 200 / [data length];
            data = UIImageJPEGRepresentation(image, compress);
        }
        [formData appendPartWithFileData:data name:fileName fileName:[NSString stringWithFormat:@"%@.jpg",imageName] mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"url - %@,\n params-----%@,\n response success - %@",url,params,[responseObject mj_JSONObject]);
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"url - %@,\n params-----%@,\n response error - %@",url,params,[error mj_JSONObject]);
        if (failture) {
            failture(task,error);
        }
    }];
    //    [_manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //        // 利用时间戳当做图片名字
    //        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    //        formatter.dateFormat = @"yyyyMMddHHmmss";
    //
    //        for (int i = 0; i < [images count]; i++) {
    //
    //            NSString * imageName = [formatter stringFromDate:[NSDate date]];
    //            NSString * fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
    //
    //            UIImage * image = images[i];
    //            NSData * data = UIImageJPEGRepresentation(image, 1);
    //
    //            // 如果图片大于1M  将图片压缩到200kb左右
    //            if ([data length] > 1024000) {
    //                CGFloat compress = 200 / [data length];
    //                data = UIImageJPEGRepresentation(image, compress);
    //            }
    //
    //            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
    //        }
    //
    //    } progress:progress success:success failure:failture];
}



#pragma mark - 文件下载
- (void)requestFileDownloadWithPath:(NSString *)path
                           progress:(void(^)(NSProgress * uploadProgress))progress
                           complete:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))complete
{
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    NSURLSessionDownloadTask * loadTask = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            progress(downloadProgress);
        }
        
        //下载进度监听
        //    NSLog(@"Progress:----%.2f%",100.0*downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"fullPath:%@",fullPath);
        NSLog(@"targetPath:%@",targetPath);
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        complete(response,filePath,error);
        
        NSString * path = [filePath.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"filePath:%@",filePath);
        
        if (error) {
            
        } else {
            
            // 下载成功，将文件放入Document/QYMPAcc文件下
            NSFileManager * file = [NSFileManager defaultManager];
            NSString * document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString * mpaccPath = [document stringByAppendingPathComponent:@"QYMPAccFile"];
            if (![[NSFileManager defaultManager] fileExistsAtPath:mpaccPath]) {
                [[NSFileManager defaultManager] createDirectoryAtPath:mpaccPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            
            NSString * filepathssss = [path componentsSeparatedByString:@"file://"][1];
            NSString * newPath = [mpaccPath stringByAppendingPathComponent:[path componentsSeparatedByString:@"/Library/Caches/"][1]];
            NSLog(@"filepathssss - :%@",filepathssss);
            NSLog(@"mpaccPath - :%@",newPath);
            NSError * errrrrr = nil;
            if ([file moveItemAtPath:filepathssss toPath:newPath error:&errrrrr]) {
                NSLog(@"下载文件放入Document成功");
            } else {
                NSLog(@"下载文件放入Document失败");
                NSLog(@" --- %@",errrrrr.localizedDescription);
            }
        }
    }];
    [loadTask resume];
}


#pragma mark - 文件下载
- (void)requestFileDownloadWithPath:(NSString *)path
                           fileName:(NSString *)fileName
                           progress:(void(^)(NSProgress * uploadProgress))progress
                           complete:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))complete
{
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    NSURLSessionDownloadTask * loadTask = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (progress) {
            progress(downloadProgress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"fullPath:%@",fullPath);
        NSLog(@"targetPath:%@",targetPath);
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        complete(response,filePath,error);
        
        NSString * path = [filePath.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"filePath:%@",filePath);
        
        if (error) {
            
        } else {
            
            // 下载成功，将文件放入Document/QYMPAcc文件下
            NSFileManager * file = [NSFileManager defaultManager];
            NSString * document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString * mpaccPath = [document stringByAppendingPathComponent:@"QYMPAccFile"];
            if (![[NSFileManager defaultManager] fileExistsAtPath:mpaccPath]) {
                [[NSFileManager defaultManager] createDirectoryAtPath:mpaccPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            
            NSString * filepathssss = [path componentsSeparatedByString:@"file://"][1];
            NSString * newPath = [mpaccPath stringByAppendingPathComponent:[path componentsSeparatedByString:@"/Library/Caches/"][1]];
            NSLog(@"filepathssss - :%@",filepathssss);
            NSLog(@"mpaccPath - :%@",newPath);
            NSError * errrrrr = nil;
            if ([file moveItemAtPath:filepathssss toPath:newPath error:&errrrrr]) {
                NSLog(@"下载文件放入Document成功");
            } else {
                NSLog(@"下载文件放入Document失败");
                NSLog(@" --- %@",errrrrr.localizedDescription);
            }
        }
    }];
    [loadTask resume];
}


@end


#endif
